"""A sample skeleton vehicle app."""

import asyncio
import json
import logging

from sdv.util.log import (  # type: ignore
    get_opentelemetry_log_factory,
    get_opentelemetry_log_format,
)
from sdv.vdb.reply import DataPointReply
from sdv.vehicle_app import VehicleApp, subscribe_topic
from vehicle import Vehicle  # type: ignore

# Configure the VehicleApp logger with the necessary log config and level.
logging.setLogRecordFactory(get_opentelemetry_log_factory())
logging.basicConfig(format=get_opentelemetry_log_format())
logging.getLogger().setLevel("DEBUG")
logger = logging.getLogger(__name__)

GET_BACK_REQUEST_TOPIC = "backlight/setBackup/request"
GET_BACK_RESPONSE_TOPIC = "backlight/setBackup/response"


class BackLightApp(VehicleApp):

    def __init__(self, vehicle_client: Vehicle):
        # SampleApp inherits from VehicleApp.
        super().__init__()
        self.Vehicle = vehicle_client
        self.flag = True

    async def on_start(self):
        """Run when the vehicle app starts"""
        # This method will be called by the SDK when the connection to the
        # Vehicle DataBroker is ready.
        # Here you can subscribe for the Vehicle Signals update
        # (e.g. Vehicle.Body.Lights.IsBackupOn).
        # loop = asyncio.get_running_loop()
        # loop.create_task(self.on_timer())
        pass

    async def on_timer(self):
        while 1:
            logging.debug("task loopping ...")
            await self.Vehicle.Body.Lights.IsBackupOn.set(self.flag)
            self.flag = not self.flag
            await asyncio.sleep(0.5)

    @subscribe_topic(GET_BACK_REQUEST_TOPIC)
    async def on_get_back_request_received(self, data_str: str) -> None:

        logger.debug(
            "PubSub event for the Topic: %s -> is received with the data: %s",
            GET_BACK_REQUEST_TOPIC,
            data_str,
        )

        back_value = (await self.Vehicle.Body.Lights.IsBackupOn.get()).value
        
        data = json.loads(data_str)
        
        status = data["status"]
        if status:
            message = "on"
        else:
            message = "off"
        if status != back_value:
            await self.publish_event(
                GET_BACK_RESPONSE_TOPIC,
                json.dumps(
                    {
                        "result": {
                            "status": 0,
                            "message": f"""back light change to {message}""",
                        },
                    }
                ),
            )
        else:
            await self.publish_event(
                GET_BACK_RESPONSE_TOPIC,
                json.dumps(
                    {
                        "result": {
                            "status": 0,
                            "message": f"""back light had already {message}""",
                        },
                    }
                ),
            )
